﻿using SqlSugar;
using SqlSugar.IOC;
using SqlsugarBlog.IRepository;
using SqlsugarBlog.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlsugarBlog.Repository
{
    /// <summary>
    /// 基础仓储
    /// SimpleClient<T>：必须继承该类，并且在构造方法中注入ISqlSugarClient
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> : SimpleClient<T>, IBaseRepository<T> where T : class, new()
    {
        public BaseRepository(ISqlSugarClient db):base(db)//因为不需要切换仓储所以可以直接用构造函数获取db
        {
            base.Context = db;

            //创建数据库和表仅需创建一次即可
            //创建数据库
            //db.DbMaintenance.CreateDatabase();
            //创建表
            //db.CodeFirst.InitTables(
            //    typeof(BlogNews),
            //    typeof(BlogType),
            //    typeof(WritterInfo)
            //    );
        }
        public async Task<bool> AddAsync(T entity)
        {
            return await base.InsertAsync(entity);
        }

        public async Task<bool> DeleteAsync(int id)
        {
            return await base.DeleteByIdAsync(id);
        }

        public async Task<bool> ModifyAsync(T entity)
        {
            return await base.UpdateAsync(entity);
        }
        public async Task<List<T>> QueryAsync()
        {
            return await base.GetListAsync();
        }

        public async Task<List<T>> QueryAsync(System.Linq.Expressions.Expression<Func<T, bool>> expression)
        {
            return await base.GetListAsync(expression);
        }

        public async Task<List<T>> QueryAsync(int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<T>().ToPageListAsync(page,size, total);
        }

        public async Task<List<T>> QueryAsync(System.Linq.Expressions.Expression<Func<T, bool>> expression, int page, int size, RefAsync<int> total)
        {
            return await base.Context.Queryable<T>()
                .Where(expression)
                .ToPageListAsync(page, size, total);  
        }

        public async Task<T> QueryByIdAsync(int id)
        {
            return await base.GetByIdAsync(id);
        }

    }
}
